package com.jt.www.job.woxuebao;

import com.jt.www.admin.order_wxb.service.BatchInsService;
import com.jt.www.dao.mapper.woxuebao.InsBatchEntityMapper;
import com.jt.www.domain.enums.common.IsOrNotEnum;
import com.jt.www.enums.issue.AppStatusEnum;
import com.jt.www.enums.woxuebao.HandlerStatusEnum;
import com.jt.www.model.param.endorse.AppDetailProParam;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.vo.endorse.AppDetailProVo;
import com.jt.www.model.woxuebao.InsBatchEntity;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.List;

/**
 * 我学保批量投保
 *
 * @author shaoyunan
 * @date 2020-09-18
 */
@Component
@EnableScheduling
public class CheckBatchInsIssueTask implements SchedulingConfigurer{

    public static final Logger log = LoggerFactory.getLogger(CheckBatchInsIssueTask.class);

    @Autowired
    InsBatchEntityMapper insBatchEntityMapper;
    @Autowired
    private InsClient insClient;
    @Autowired
    BatchInsService batchInsService;

    /**
     * 任务开关
     */
    @Value("${jtpf.batchins.issue.open}")
    private int checkOpen;

    /**
     * 任务执行周期
     */
    @Value("${jtpf.batchins.issue.cron}")
    private String cron;


    /**
     *  单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long IME_OUT = 60L;


    /**
     * 我学保批量投保
     */
    private static final String BATCH_INS_LOCK_KEY = "EDU_BATCH_INS";

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        Runnable task0 = () -> checkStart();
        Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
        taskRegistrar.addTriggerTask(task0, trigger0);
    }

    private void checkStart() {
        //多个服务同时启动定时任务，在执行体开始时判断是否有其他线程在执行
        //设置缓存失败表示有在执行的任务
        if(!RedisUtil.setLock(IME_OUT, BATCH_INS_LOCK_KEY)){
            return;
        }
        String findCode = "BATCH_INS_ISSUE_" + System.currentTimeMillis();
        try {
            log.info("{}我学保批量投保(查询保单号)开始!", findCode);
            Weekend<InsBatchEntity> weekend = Weekend.of(InsBatchEntity.class);
            WeekendCriteria<InsBatchEntity, Object> criteria = weekend.weekendCriteria();
            criteria.andEqualTo(InsBatchEntity::getHandleStatus, HandlerStatusEnum.SUCCESS_INS.getCode());
            criteria.andEqualTo(InsBatchEntity::getIsDeleted, IsOrNotEnum.NO.getValue());
            criteria.andLessThan(InsBatchEntity::getTimes, 6);
            criteria.andIsNull(InsBatchEntity::getPolicyNo);
            //从第0位开始查询，查询出前300个
            RowBounds rowBounds = new RowBounds(0, 300);
            List<InsBatchEntity> resultList = insBatchEntityMapper.selectByExampleAndRowBounds(weekend, rowBounds);
            for(InsBatchEntity insBatchEntity : resultList){
                String detailFindCode = findCode + "_" + insBatchEntity.getTbNo();
                //查询投保中心 得到保单号
                String policyNo = getPolicyNo(detailFindCode, insBatchEntity);
                //
                InsBatchEntity update = new InsBatchEntity();
                update.setId(insBatchEntity.getId());
                if(StringUtils.isNotBlank(policyNo)){
                    update.setPolicyNo(policyNo);
                    insBatchEntityMapper.updateByPrimaryKeySelective(update);
                }else{
                    update.setTimes(insBatchEntity.getTimes()+1);
                    insBatchEntityMapper.updateByPrimaryKeySelective(update);
                }
            }
        } catch (Exception e) {
            log.info("{}我学保批量投保(查询保单号)出错!", findCode);
        } finally {
            //删除缓存
            RedisUtil.delete(BATCH_INS_LOCK_KEY);
            log.info("{}我学保批量投保(查询保单号)结束!", findCode);
        }
    }

    private String getPolicyNo(String findCode, InsBatchEntity insBatchEntity){
        log.info("{}我学保批量投保(查询保单号)，投保单号:{}", findCode, insBatchEntity.getTbNo());
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProVo detailVos;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(insBatchEntity.getTbNo());
        p.setChannelCode("edu");    // 渠道编号
        p.setUserCode(insBatchEntity.getUserCode());
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            log.info("{}我学保批量投保(查询保单号)，投保单号:{}，返回结果:{}",findCode, insBatchEntity.getTbNo(), JsonUtil.object2Json(appDetailPro));
            detailVos = appDetailPro.getBody().getData();
        } catch (Exception e) {
            log.info("{}我学保批量投保(查询保单号), 查询投保单信息失败 投保单号:{}",findCode, insBatchEntity.getTbNo());
            return "";
        }
        // 待出单（08）出单失败(09) 已出单（10） 已承保(21山东险种)
        if (detailVos == null
                || AppStatusEnum.AS_99.getCode().equals(detailVos.getApplicationStatus())
                || AppStatusEnum.AS_11.getCode().equals(detailVos.getApplicationStatus())
                || AppStatusEnum.AS_12.getCode().equals(detailVos.getApplicationStatus())) {
            log.info("{}我学保批量投保(查询保单号), 查询投保单信息异常或保单失效，投保单号:{}",findCode, insBatchEntity.getTbNo());
            batchInsService.updateHandleStatusById(insBatchEntity.getId(), HandlerStatusEnum.LOSE_EFFICACY, 0);
            return "保单状态失效";
        }
        return detailVos.getPolicyNo();
    }


}
